package com.study.spmongodb.book.wwj.char22;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author MI
 * @version 1.0
 * @date 2020/11/30 16:53
 */
public class Document {
    //如果文档发生变化，changed会设置为true
    private boolean changed = false;

    //一次需要保存的内容，可以将其理解为内容缓存
    private List<String> content = new ArrayList<>();

    private final FileWriter writer;

    private static AutoSaveThread autoSaveThread;

    private Document(String documentPath, String documentName) throws IOException {
        this.writer = new FileWriter(new File(documentPath, documentName), false);
    }

    //静态方法，主要用于创建文档，顺便自动保存文档的线程
    public static Document create(String documentPath, String documentName) throws IOException {

        final Document document = new Document(documentPath, documentName);
        autoSaveThread = new AutoSaveThread(document);
        autoSaveThread.start();
        return document;
    }

    /**
     * 文档的编辑，其实就是往content队列中提交字符串
     *
     * @param content
     */
    public void edit(String content) {
        synchronized (this) {
            this.content.add(content);
            //文档改变。change会变为true
            this.changed = true;
        }
    }

    /**
     * 文旦关闭 时首先 中断自动保存线程，然后关闭write 释放资源
     *
     * @throws IOException
     */
    public void close() throws IOException {
        autoSaveThread.interrupt();
        writer.close();
    }

    /**
     * save 方法用于外部显示进行文档保存
     *
     * @throws IOException
     */
    public void save() throws IOException {
        synchronized (this) {
            //如果文档已经保存了，直接返回
            if (!changed) {
                return;
            }
            System.out.println(Thread.currentThread().getName() + " execute the save action");
            //将内容写入文档中
            for (String chcheLine : content) {
                this.writer.write(chcheLine);
                this.writer.write("\r\n");
            }

            this.writer.flush();
            ;
            //将 changed修改为false，表明此刻再没有新的内容编辑
            this.changed = false;
            this.content.clear();
        }
    }

}
